<?php
	
	/**
	 * 收货地址模型
	 */
	 class ReceiveAddrModel extends Model{
	 		
		public $validate = array(
			array('re_name','nonull','收货人不能为空',2,3),
			array('re_addarea','nonull','收货地区不能为空',2,3),
			array('re_address','nonull','详细地址不能为空',2,3),
			array('re_phone','nonull','联系电话不能为空',2,3),
			array('re_zipcode','nonull','邮编不能为空',2,3)
		);
		
		/**
		 * 修改收货地址
		 */
		 public function editAddr(){
		 	if(!$this->create()) return false;
			$data = $this->data;
			if($this->where("reid={$data['reid']}")->save($data)){
				return true;
			}else{
				$this->error = '修改失败';
				return false;
			}
		 }
		
		/**
		 * 添加一条收货地址
		 */
		 public function addAddr(){
		 	if(!$this->create()) return false;
			
			if($this->add()){
				return true;
			}else{
				$this->error = '添加失败';
				return false;
			}
		 }
		 
		 /*
		  * 修改一个收货地址
		  */
		 public function ajaxEditAddr(){
		 	$_POST['re_addarea'] = $_POST['prov'].','.$_POST['city'].','.$_POST['dist'];
		 	if(!$this->create()) return false;
			$data = $this->data;
			if($this->save($data)){
				$data['address'] = $this->returnAddr($data['re_addarea'],$data['re_address']);
				return $data;
			}else{
				return false;
			}
		 }
		 
		
		/**
		 *  获得相应的UID所有收货地址
		 */
		public function getUserRa($uid){
			$arr = array();
			$result = $this->where("uid={$uid}")->order('is_default DESC')->limit(10)->all();
			//遍历每个收货地址返回一个详细的收货地址给相应的数组
			foreach($result as $r){
				$r['address']  = $this->returnAddr($r['re_addarea'],$r['re_address']);
				$arr[] = $r;
			}
			return $arr;
		}
		
		/**
		 * 返回一个组合好的相应地址ID的地址
		 */
		 public function takeAddr($reid){
		 	$result = $this->where("reid={$reid}")->find();
			$result['address'] = $this->returnAddr($result['re_addarea'],$result['re_address']);
			return $result;
		 }
		
		
		
		/**
		 * 返回一个地区地址
		 * 返回的内容 ：省份--高级--县级 详细地址
		 */
		public function returnAddr($area,$address){
			$str = '';
			
			$cityIds = explode(',',rtrim($area,','));
			
			//省份名
			$prov = $cityIds[0];
			$str .= $this->table('province')->where("provid={$prov}")->find()['provname'].'--';
			//城市名
			$cityid = $cityIds[1];
			$str .= $this->table('city')->where("cityid={$cityid}")->find()['cityname'].'--';
			//县名
			if(!isset($cityIds[2]) || !empty($cityIds[2] || $cityIds[2] !=0)){
				$distid = $cityIds[2];
				$str .= $this->table('district')->where("distid={$distid}")->find()['dist_name'];
			}

			return $str.$address;				
		}
		
		
		/**
		 * 用户中心添加收货地址
		 * 
		 */
		 public function addAddrUser(){
		 	$_POST['re_addarea'] = $_POST['re_addarea'] = $_POST['prov'].','.$_POST['city'].','.$_POST['dist'];
		 	if(!$this->create()) return false;
			$data = $this->data;
			$reid = $this->add($data);
			if($reid){
				return $this->takeAddr($reid);
			}else{
				return false;
			}
		 }
		
		
		
	 }

